# -*- coding: utf-8 -*-
"""
decorator functions

to use with your views
"""
##
# @author J.Ducastel <nospam0@ducastel.name>

# imports
from django.shortcuts import render_to_response
from django.template import RequestContext

import settings
from api import get_or_create_user, get_user, NoUserLogged

# exceptions
from api import Forbidden, Http403, Http405

# classes et fonctions

def _call_intercept(view, request, *args, **kw):
    """calls view but intercepts Http403 errors"""
    try:
        r =  view(request, *args, **kw)
        return r
    except Http403, exception:
        # rendering project 403 or defaulting to self
        r = render_to_response(
            ['403.html', 'noaccount/403.html'],
            RequestContext(request, locals()))
        r.status_code = 403
        return r


def user_required(view):
    """Decorator for views that sets request.user

    Searches for session_logged user. If not found,
    creates an user and add it to session and request."""
    def inner(request, *args, **kw):
        try:
            request.user = get_or_create_user(request)
            return _call_intercept(view, request, *args, **kw)
        except Forbidden:
            # rendering project 403 or defaulting to self
            r = render_to_response(
                ['403.html', 'noaccount/403.html'],
                RequestContext(request, locals()))
            r.status_code = 403
            return r
    return inner

def user_if_available(view):
    """
    Decorator for views that sets request.user
    if available, else unsaved user 
    """
    def inner(request, *args, **kw):
        try:
            request.user = get_user(request)
        except NoUserLogged:
            # 403 ?
            request.user = None
        return _call_intercept(view, request, *args, **kw)
    return inner